//
//  HLIMKitMessageAudioContentView.m
//  YueYue
//
//  Created by hulu001 on 2024/1/12.
//

#import "HLIMKitMessageAudioContentView.h"
#import "HLIMKitMessageModel.h"
#import "HLIMKitEvent.h"
#import "HLIMKitAudioCenter.h"

NSString *const HLIMKitEventNameTapAudio = @"HLIMKitEventNameTapAudio";
NSString *const HLIMKitEventNameTapAudioPlain = @"HLIMKitEventNameTapAudioPlain";

@interface HLIMKitMessageAudioContentView ()<NIMMediaManagerDelegate>
@property (nonatomic, strong) UILabel *timeLabel;
@property (nonatomic, strong) UIImageView *icon;

@property (nonatomic, assign) NSInteger status; // 0:默认 1:更新了铭文 2：更新了翻译
@property (nonatomic, assign) NSTimeInterval voiceTime;

@end

@implementation HLIMKitMessageAudioContentView


- (void)dealloc
{
    [NIMSDK.sharedSDK.mediaManager removeDelegate:self];
}

- (instancetype)init
{
    self = [super init];
    if (self) {
        self.timeLabel = [UILabel.alloc init];
        self.timeLabel.textColor = [UIColor colorWithRed:31/255.0 green:31/255.0 blue:31/255.0 alpha:1.000000];
        self.timeLabel.font = [UIFont systemFontOfSize:14];
        [self addSubview:self.timeLabel];
        
        self.icon = [UIImageView.alloc initWithFrame:CGRectMake(0, 0, 20, 20)];
        [self addSubview:self.icon];
        
        [NIMSDK.sharedSDK.mediaManager addDelegate:self];
    }
    return self;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    [self.timeLabel sizeToFit];
    
    UIEdgeInsets insets = self.messageModel.contentViewInsets;
    
    if (self.messageModel.message.isOutgoingMsg) {
        // 时长
        self.icon.right = self.width - insets.right;
        self.icon.centerY = self.middleY;
        // 动图
        self.timeLabel.right = self.icon.left - 6;
        self.timeLabel.centerY = self.middleY;
    } else {
        self.icon.left = insets.left;
        self.icon.centerY = self.middleY;
        self.timeLabel.left = self.icon.right + 6;
        self.timeLabel.centerY = self.middleY;
    }
}

- (void)refreshData:(HLIMKitMessageModel *)messageModel
{
    [super refreshData:messageModel];
    
    NIMMessage * message = messageModel.message;
    NIMAudioObject *messageObject = (NIMAudioObject *)message.messageObject;
    NSTimeInterval recordtimes = messageObject.duration/1000;
    self.voiceTime = recordtimes;
    NSInteger minutes = (NSInteger)recordtimes / 60;
    NSInteger seconds = (NSInteger)recordtimes % 60;
    if (minutes > 0) {
        self.timeLabel.text = [NSString stringWithFormat:@"%zd'%zd''", minutes, seconds];
    } else {
        self.timeLabel.text = [NSString stringWithFormat:@"%zd'", seconds];
    }
    
    if (self.messageModel.seekTime > 0) {
        
    }
    
    
    if (message.isOutgoingMsg) {
        self.timeLabel.textColor = [UIColor colorWithRed:36/255.0 green:41/255.0 blue:51/255.0 alpha:1.0]; // 更改时间颜色
        if ([self isPlaying]) {
            [self startPlaying];
        } else {
            self.icon.image = [UIImage imageNamed:@"sender_voice_playing_03"];
        }
    } else {
        self.timeLabel.textColor = [UIColor colorWithRed:36/255.0 green:41/255.0 blue:51/255.0 alpha:1.0];// 更改时间颜色
        if ([self isPlaying]) {
            [self startPlaying];
        } else {
            self.icon.image = [UIImage imageNamed:@"receiver_voice_playing_03"];
        }
    }
}

- (void)onTouchUpInside:(id)sender
{
    if ([self isPlaying])
    {
        [self stopPlaying];
    }
    
    
    if ([self.delegate respondsToSelector:@selector(onTap:)]) {
        HLIMKitEvent *event = [HLIMKitEvent.alloc init];
        event.gestureName = HLIMKitGestureTouchUpInside;
        event.eventName   = HLIMKitEventNameTapAudio;
        event.messageModel= self.messageModel;
        [self.delegate onTap:event];
    }
}

- (void)longPress:(UILongPressGestureRecognizer *)gesture
{
    if (gesture.state == UIGestureRecognizerStateBegan) {
        self.plainView.backgroundColor = [UIColor.whiteColor colorWithAlphaComponent:0.2];
        self.messageModel.message.messageSubType = 1;
        [self.delegate onLongTap:self.messageModel.message onView:self.plainView];
    } else  {
        if (gesture.state == UIGestureRecognizerStateEnded) {
            self.plainView.backgroundColor = UIColor.clearColor;
        }
        
        if (![self location:gesture onView:self.plainView]) {
            self.plainView.backgroundColor = UIColor.clearColor;
        }
    }
}

/// 检测手势位置是否在某个view
/// @param gesture 手势
/// @param view 要检测的view
- (BOOL)location:(UIGestureRecognizer *)gesture onView:(UIView *)view
{
    CGPoint point = [gesture locationInView:view];
    
    if (point.x < 0 || point.y < 0) return NO;
    
    if (point.x > CGRectGetWidth(view.frame) || point.y > CGRectGetHeight(view.frame)) return NO;
    
    return YES;
}

- (void)startPlaying
{
    if (self.messageModel.message.isOutgoingMsg) {
        NSArray *animateIcons = @[[UIImage imageNamed:@"sender_voice_playing_01"],
                                  [UIImage imageNamed:@"sender_voice_playing_02"],
                                  [UIImage imageNamed:@"sender_voice_playing_03"]];
        self.icon.animationImages = animateIcons;
    } else {
        NSArray *animateIcons = @[[UIImage imageNamed:@"receiver_voice_playing_01"],
                                  [UIImage imageNamed:@"receiver_voice_playing_02"],
                                  [UIImage imageNamed:@"receiver_voice_playing_03"]];
        self.icon.animationImages = animateIcons;
    }
    self.icon.animationDuration = 1;
    self.icon.animationRepeatCount = 0;
    [self.icon startAnimating];
}

/// 暂停播放
- (void)pausePlaying
{
    if (self.messageModel.message.isOutgoingMsg) {
        self.icon.image = [UIImage imageNamed:@"rightAudioPlay"];
    } else {
        self.icon.image = [UIImage imageNamed:@"leftAudioPlay"];
    }
}

/// 停止播放
- (void)stopPlaying
{
    [self.icon stopAnimating];
}

- (BOOL)isPlaying
{
    return [HLIMKitAudioCenter.sharedCenter isPlayingMessage:self.messageModel.message];
}

#pragma mark - NIMMediaManagerDelegate

- (void)playAudio:(NSString *)filePath didBeganWithError:(NSError *)error {
    if(filePath && !error) {
        [self stopPlaying];
        if (error) return;
        
        if ([self isPlaying]) {
            [self startPlaying];
        }
    }
}

- (void)playAudio:(NSString *)filePath didCompletedWithError:(NSError *)error
{
    [self stopPlaying];
    self.messageModel.seekTime = 0;
    self.messageModel.seek = 0;
}

- (void)stopPlayAudio:(NSString *)filePath didCompletedWithError:(nullable NSError *)error
{
    [self stopPlaying];
}

- (void)playAudio:(NSString *)filePath progress:(float)value
{
    if ([self isPlaying]) {
        // 保存当前的实时总进度
        self.messageModel.seekTime = self.messageModel.seek + value * (self.voiceTime - self.messageModel.seek);
    }
}


@end
